package com.miplus.ccrm.core.service;


import com.alibaba.fastjson.JSON;
import com.miplus.ccrm.common.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.lang.Nullable;
import org.springframework.stereotype.Service;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Slf4j
@Service
public class JTokenInterceptor implements HandlerInterceptor {

    @Resource
    private JDataService dataService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws java.lang.Exception {
        String token = JPubUtils.getToken(request);
        if (JPubUtils.IsEmpty(token)) {
            log.warn("token unauthorized:{}",token);
            response.sendError(HttpServletResponse.SC_UNAUTHORIZED);
            return false;
        }
        String key = JPubUtils.getTokenKey(token);
        JSysUser user = (JSysUser) dataService.get(key);
        if (user==null) {
            log.warn("tokenexpire nofind:{} ",token);
            response.setContentType("application/json;charset=UTF-8");
            R<Object> result = R.Error(EnumRCode.TokenExpire, "authorization");
            response.getWriter().write(JSON.toJSONString(result));
            return false;
        }else{
            log.info("user:{} token.ok",user.getUsrid());
        }

        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable ModelAndView modelAndView) throws java.lang.Exception {
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable Exception ex) throws java.lang.Exception {

    }
}
